<?php
/**
 * 后台登陆控制器
 *
 * Author:李强
 * Company:上海煦鸣网络科技有限公司
 * Date:2018-01-03
 */

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\CommonController;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends CommonController
{
    /**
     * 后台登陆页面
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function loginForm(Request $request)
    {
        if(Auth::check()){
            Auth::logout();
        }
        return view('admin.login.index');
    }

    /**
     * 后台管理员登陆处理
     *
     * @param Request $request
     * @return mixed
     */
    public function doLogin(Request $request)
    {
        if ($request->ajax()) {
            $username = $request->input('username', '');
            if ($username == '') {
                return $this->error('请填写登陆名称');
            }
            $password = $request->input('password', '');
            if ($password == '') {
                return $this->error('请填写登陆密码');
            }
            $verycode = $request->input('verycode', '');
            if ($verycode == '') {
                return $this->error('请填写验证码');
            }
            $user = User::where(['mobile' => $username])->first();
            if (is_null($user)) {
                return $this->error('用户密码错误');
            }
            if ($user->status != 1) {
                return $this->error('账号异常,暂不能登陆');
            }
            if (!captcha_check($verycode)) {
                return $this->error('请填写正确的验证码');
            }
            $can_login = Auth::attempt(['mobile' => $username, 'password' => $password]);
            if (!$can_login) {
                info($user->password . " " . $password . " " . $can_login);
                return $this->error('用户密码错误1' . $user->passwrod);
            } else {
                return $this->success('登陆成功');
            }
        }
    }

    /**
     * 退出登陆操作
     *
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function logout(Request $request)
    {
        if (Auth::check()) {
            Auth::logout();
        }
        if ($request->ajax()) {
            return $this->success('退出成功', ['jump_url' => url('login')]);
        }
        return redirect('login');
    }
}
